<template>
	<a-modal
		:visible="visible"
		width="1100px"
		title="添加预定"
		centered
		destroyOnClose
		:maskClosable="false"
		@cancel="cancel"
		:bodyStyle="{padding: 0}">
		<a-form ref="formRef" class="flex-container-nomal" style="height: 70vh" :model="modelRef" :rules="formRules" layout="vertical">
			<div class="flex1 auto-y">
				<div class="flex-container-nomal">
					<a-row :gutter="16">
						<a-col :span="10">
							<a-form-item name="bookType">
								<template #label>
									支付方式
									<small v-if="modelRef.bookType === 2" v-color="{color: 'warning'}">
										（租客需在1小时内在线支付定金，如逾期定金将失效）
									</small>
								</template>
								<a-select v-model:value="modelRef.bookType" :options="payMethodOptions" placeholder="请选择支付方式" />
							</a-form-item>
						</a-col>
						<a-col :span="14">
							<a-form-item label="房源地址" name="houseId">
								<!--<a-input-group compact style="display: flex">-->
								<!--	<a-form-item-rest>-->
								<!--		<a-select :disabled="!!houseRecord" v-model:value="modelRef.houseType" :options="housingType" @change="handleChange(null)" style="width: 120px" />-->
								<!--	</a-form-item-rest>-->
								<a-select :disabled="!!houseRecord" v-model:value="modelRef.houseId" v-bind="searchOptions" style="flex: 1">
									<template v-if="loadings.search" #notFoundContent>
										<a-spin spinning tip="正在搜索，请稍候……" />
									</template>
								</a-select>
								<!--</a-input-group>-->
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-typography-text strong>
								<blockquote>预定信息</blockquote>
							</a-typography-text>
						</a-col>
						<a-col :span="6">
							<a-form-item label="姓名" name="name">
								<a-input-group compact>
									<!-- style="width: calc(100% - 91px)" -->
									<a-input v-model:value="modelRef.name" placeholder="请输入姓名" />
									<!-- <a-form-item-rest>
										<a-radio-group v-model:value="modelRef.gender" button-style="solid">
											<a-radio-button v-for="(v, k) in sexList" :key="k" :value="Number(k)">{{ v }}</a-radio-button>
										</a-radio-group>
									</a-form-item-rest> -->
								</a-input-group>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="手机号码" name="phone">
								<a-input v-model:value="modelRef.phone" :maxlength="11" placeholder="请输入手机号码" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="证件类型" name="certificateType">
								<a-select
									v-model:value="modelRef.certificateType"
									:options="certificateOptions"
									placeholder="请选择证件类型"
									@change="formRef.resetFields('certificateNo')" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="证件号码" name="certificateNo">
								<a-input v-model:value="modelRef.certificateNo" :maxlength="18" placeholder="请输入证件号码" />
							</a-form-item>
						</a-col>
						<a-col :span="6" v-if="modelRef.bookType === 1">
							<a-form-item label="收支类型" name="isOccur">
								<a-select v-model:value="modelRef.isOccur" :options="feeDirectionList" placeholder="请选择收支类型" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="预定金额" name="money">
								<!-- <a-input-number v-model:value="modelRef.money" :min="0" :max="maxAmount" :precision="2" placeholder="请输入预定金额" style="width: 100%" /> -->
								<a-input-number
									v-model:value="modelRef.money"
									:min="0"
									:disabled="isMoneyDisabled"
									:precision="2"
									placeholder="请输入预定金额"
									style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="最晚签约日期" name="signDate">
								<a-date-picker
									v-model:value="modelRef.signDate"
									placeholder="请选择最晚签约日期"
									:value-format="DATE_FORMAT.DATE"
									:disabledDate="disabledDate"
									:allowClear="false"
									style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="预计租住年限" name="contractMonth">
								<a-select
									v-model:value="modelRef.contractMonth"
									placeholder="请选择预计租住年限"
									:options="rentYearsList" />
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.isOccur === 1 && modelRef.bookType === 1" :span="12">
							<a-form-item label="支付时间" name="practicalTime" :rules="[{required: true, message: '请选择支付时间'}]">
								<a-date-picker
									:show-time="{format: 'HH:mm'}"
									v-model:value="modelRef.practicalTime"
									value-format="YYYY-MM-DD HH:mm:ss"
									:disabled-date="disabledDatePayMent"
									@change="changeDateTime" />
							</a-form-item>
						</a-col>
						<a-col v-if="modelRef.isOccur === 1 && modelRef.bookType === 1" :span="12">
							<a-form-item name="paymentMethod" label="支付方式" :rules="[{required: true, message: '请选择支付方式'}]">
								<a-input-group compact class="display-flex">
									<a-form-item-rest>
										<a-select
											v-model:value="modelRef.paymentMethod"
											:options="paymentMethods"
											placeholder="支付方式"
											:field-names="{label: 'name', value: 'id'}"
											style="width: 120px" />
										<a-input v-model:value="modelRef.paymentAccount" placeholder="请输入收款账户" style="flex: 1" />
									</a-form-item-rest>
								</a-input-group>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="备注" name="comment">
								<a-textarea
									v-model:value="modelRef.comment"
									placeholder="请输入备注"
									:rows="4"
									show-count
									:maxlength="500" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="附件" name="fileList" class="margin-none">
								<file-upload v-model:files="modelRef.fileList" show-qr-code show-tips />
							</a-form-item>
						</a-col>
					</a-row>
				</div>
			</div>
		</a-form>
		<template #footer>
			<a-button type="primary" :disabled="loadings.save" :loading="loadings.save" @click="submit">保存</a-button>
		</template>
	</a-modal>
</template>
<script setup lang="ts">
	import {reactive, ref, watchEffect, onBeforeMount, watch} from 'vue'
	import {FormInstance, message} from 'ant-design-vue'
	import {addContractBook, getHouseBookRule, searchByAddress} from '@/api/contract'
	import {rentYears, sexList} from '@/utils'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import {rules} from '@/utils/rules'
	import {checkIdCard} from '@/utils/check'
	import type {Rule} from 'ant-design-vue/es/form'
	import dayjs, {Dayjs} from 'dayjs'
	import FileUpload from '@/components/common/file-upload.vue'
	import XEUtils from 'xe-utils'
	import {HouseBase} from '@/interface/house'
	import {isLockinEnv} from 'yuxin-base/src/utils'
	import DATE_FORMAT, {nowDateTime} from 'yuxin-base/src/utils/date'
	import SettingApi from 'yuxin-base/src/api/setting-api'
	import {DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {Modal} from 'ant-design-vue'

	const props = defineProps<{
		visible: boolean
		houseRecord?: HouseBase
		/** 是否提前预定 */
		isPreBook?: boolean
	}>()
	// 付款方式
	const paymentMethods = ref<any[]>([])

	const loadings = reactive({
		save: false,
		search: false
	})

	const getPreBookDays = ref(null)
	const modelRef = reactive<any>({
		bookType: 1,
		houseType: 0,
		houseId: null,
		houseAddress: null,
		housePid: null,
		maintainerId: null,
		name: null,
		gender: 1,
		phone: null,
		certificateType: 1,
		certificateNo: null,
		isOccur: 1,
		money: null,
		signDate: null,
		contractMonth: 12,
		comment: null,
		nation: null,
		fileList: [],
		attachmentIds: [],
		// 支付方式
		paymentMethod: '',
		// 支付时间
		practicalTime: dayjs(new Date()).format(DATE_FORMAT.DATETIME),
		// 支付账号
		paymentAccount: null
	})

	const maxAmount = ref<number>(0)

	const formRules = {
		...rules,
		houseId: [{required: true, message: '请选择房源地址'}],
		certificateNo: [
			{
				validator: async (_rule: Rule, value: string) => {
					if (modelRef.certificateType == 1) {
						if (value) {
							if (!checkIdCard(value)) {
								return Promise.reject('证件号码格式不正确')
							} else {
								return Promise.resolve()
							}
						} else {
							return Promise.resolve()
						}
					} else {
						return Promise.resolve()
					}
				}
			}
		]
	}

	const payMethodOptions = [
		{
			value: 1,
			label: '线下支付定金'
		},
		{
			value: 2,
			label: '线上支付定金'
		}
	]
	const isMoneyDisabled = ref(false)
	const certificateOptions = Object.keys(CERTIFICATION_TYPE_MAP).map((key: string) => ({
		label: CERTIFICATION_TYPE_MAP[key],
		value: Number(key)
	}))
	const rentYearsList = Object.keys(rentYears).map((key: string) => ({
		label: rentYears[key],
		value: Number(key)
	}))
	const feeDirectionList = [
		{
			label: '已收',
			value: 1
		}
		// {
		// 	label: '未收',
		// 	value: 2
		// }
	]

	// 房源搜索结果
	const houseData = ref<any[]>([])
	const searchOptions = reactive<any>({
		options: houseData,
		showSearch: true,
		filterOption: false,
		placeholder: '请输入房源地址进行搜索',
		fieldNames: {
			label: 'address',
			value: 'houseRoomId'
		},
		onSearch(like: string) {
			if (!like && !like.trim()) {
				return
			}

			handleSearch(like)
		},
		onSelect(value: string, option: any) {
			handleChange(value, option)
		}
	})

	const handleSearch = XEUtils.debounce((like: string) => {
		let params = {
			houseType: modelRef.houseType,
			like,
			current: 1,
			bizType: 3,
			size: 9999,
			hasHouseType: true,
			statusInCondition: [11],
			preBookDays: getPreBookDays.value
		}

		loadings.search = true
		searchByAddress(params)
			.then((res: any) => {
				houseData.value = res.data.records
				if (props?.houseRecord?.houseAddress && res.data.records.length === 1) {
					handleChange(houseData.value[0].houseRoomId, houseData.value[0])
				}
			})
			.finally(() => (loadings.search = false))
	}, 300)

	const handleChange = (value: string, option: any = {}) => {
		if (!value) {
			houseData.value = []
		}
		modelRef.houseId = value
		modelRef.houseAddress = option.address
		modelRef.housePid = option.houseBaseId
		modelRef.maintainerId = option.houseMaintainersId
		if (maxAmount.value && option.actualPrice) {
			modelRef.money = XEUtils.multiply(XEUtils.multiply(maxAmount.value, option.actualPrice), 0.01)
		} else {
			modelRef.money = modelRef.money || 0
		}
		isMoneyDisabled.value = modelRef.money ? true : false
		// maxAmount.value = option.actualPrice
	}

	const maxDate = ref<any>('')
	const minDate = ref<any>('')
	const getOptions = async () => {
		// 获取预定规则
		// 用await 必须先获取到预定规则才能搜索符合预定需求的房源
		const res = await getHouseBookRule()
		if (!res.data) {
			Modal.warning({
				title: () => '提示',
				content: () => '预定规则未配置，还请配置完预定规则再操作！'
			})
		}
		if (props.isPreBook) {
			if (props.houseRecord?.renterContract?.endTime) {
				// 包括了当天的日期(待产品确定是否包括当天)
				maxDate.value = dayjs(props.houseRecord?.renterContract?.endTime)
					.subtract(1, 'day')
					.add(res.data.day, 'day')
					.format(DATE_FORMAT.DATE)
				minDate.value = dayjs(props.houseRecord?.renterContract?.endTime).subtract(1, 'day').format(DATE_FORMAT.DATE)
				modelRef.signDate = dayjs(props.houseRecord?.renterContract?.endTime)
					.subtract(1, 'day')
					.add(res.data.day, 'day')
					.format(DATE_FORMAT.DATE)

				// 不包括当天
				// maxDate.value = dayjs(props.houseRecord?.renterContract?.endTime).add(res.data.day, 'day').format(DATE_FORMAT.DATE)
				// minDate.value = dayjs(props.houseRecord?.renterContract?.endTime).format(DATE_FORMAT.DATE)
				// modelRef.signDate = dayjs(props.houseRecord?.renterContract?.endTime).add(res.data.day, 'day').format(DATE_FORMAT.DATE)
			} else {
				maxDate.value = dayjs().subtract(1, 'day').add(res.data.day, 'day').format(DATE_FORMAT.DATE)
				modelRef.signDate = dayjs().subtract(1, 'day').add(res.data.day, 'day').format(DATE_FORMAT.DATE)
				minDate.value = dayjs().subtract(1, 'day').format(DATE_FORMAT.DATE)
			}
		} else {
			maxDate.value = dayjs().subtract(1, 'day').add(res.data.day, 'day').format(DATE_FORMAT.DATE)
			modelRef.signDate = dayjs().subtract(1, 'day').add(res.data.day, 'day').format(DATE_FORMAT.DATE)
		}
		//1 固定 2比例
		if (res.data.rule === 1) {
			modelRef.money = res.data.num
			isMoneyDisabled.value = modelRef.money ? true : false
		} else {
			maxAmount.value = res.data.num
		}
		getPreBookDays.value = res.data.preBookDays //获取预定规则设定的可提前预定天数
		console.log('endTime', props.houseRecord?.renterContract?.endTime)

		disabledDate(new Date())
	}
	const disabledDate = (currentDate: any) => {
		// 包括当天
		if (props.isPreBook) {
			return maxDate.value
				? dayjs().isAfter(currentDate, 'day') || currentDate > new Date(maxDate.value) || currentDate < new Date(minDate.value)
				: dayjs(props.houseRecord?.renterContract?.endTime ?? '').isAfter(currentDate, 'day')
		}
		return maxDate.value
			? dayjs().isAfter(currentDate, 'day') || currentDate > new Date(maxDate.value) || currentDate < new Date(minDate.value)
			: dayjs().isAfter(currentDate, 'day')

		/** 不包括当天
		if (props.isPreBook) {
			return maxDate.value ? dayjs().add(1, 'day').isAfter(currentDate, 'day') || currentDate > new Date(maxDate.value) || currentDate < new Date(minDate.value) : dayjs(props.houseRecord?.renterContract?.endTime ?? '').isAfter(currentDate, 'day')
		}
		return maxDate.value ? dayjs().add(1, 'day').isAfter(currentDate, 'day') || currentDate > new Date(maxDate.value) || currentDate < new Date(minDate.value) : dayjs().isAfter(currentDate, 'day')
		*/
	}

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		emit('update:visible', false)
		resetForm()
	}

	watchEffect(() => {
		if (props.visible) {
			getOptions()

			if (props.houseRecord && props.houseRecord.houseRoomId) {
				houseData.value = [props.houseRecord]
				modelRef.houseId = props.houseRecord.houseRoomId
				handleSearch(props.houseRecord.houseAddress)
				// maxAmount.value = props.houseRecord.actualPrice ||
			}
			SettingApi.getDicListByPid(DIC_PID_MAP['PAYMENTMETHOD@PAYMENTMETHOD']).then(({data}) => {
				paymentMethods.value = data
				modelRef.paymentMethod = paymentMethods.value[0].id
			})
		}
	})
	watch(
		() => modelRef.bookType,
		newVal => {
			if (newVal === 1) {
				modelRef.practicalTime = dayjs(new Date()).format(DATE_FORMAT.DATETIME)
			} else {
				modelRef.practicalTime = null
			}
		}
	)

	watch(
		() => modelRef.isOccur,
		newVal => {
			if (newVal === 1) {
				modelRef.practicalTime = dayjs().format(DATE_FORMAT.DATETIME)
			} else {
				modelRef.practicalTime = null
			}
		}
	)

	const formRef = ref<FormInstance>()

	const submit = () => {
		formRef.value?.validate().then(() => {
			const params = {...modelRef}
			params.attachmentIds = params.fileList.map((o: any) => o.id)
			params.signDate = params.signDate + ' 23:59:59'
			// 线上预定不可设置已收
			if (params.bookType == 2) {
				delete params.isOccur
			}
			loadings.save = true
			// 提前预定标识
			if (props.isPreBook) params.isPreBook = true
			addContractBook(params)
				.then(() => {
					cancel()
					emit('success')
					message.success('预定添加成功')
				})
				.finally(() => (loadings.save = false))
		})
	}

	// 重置表单
	const resetForm = () => {
		modelRef.houseType = 0
		modelRef.gender = 1
		houseData.value = []
		maxAmount.value = 0
		isMoneyDisabled.value = false
		formRef.value?.resetFields()
	}

	// 支付时间日期禁用
	const disabledDatePayMent = (current: Dayjs) => {
		return current && current > dayjs().endOf('day')
	}
	const range = (start: number, end: number) => {
		const result = []

		for (let i = start; i < end; i++) {
			result.push(i)
		}

		return result
	}
	// 支付时间日期时分秒禁用
	const disabledDateTime = () => {
		// return {
		// 	disabledHours: () => range(0, 24).splice(Number(modelRef.practicalTime?.slice(11, 13)) + 1, 24),
		// 	disabledMinutes: () => range(modelRef.practicalTime?.slice(14, 16), 60),
		// 	disabledSeconds: () => [0, 60]
		// }
	}

	// 日期变化时触发
	const changeDateTime = (date: any) => {
		if (dayjs(date).isAfter(nowDateTime())) {
			message.warning('设定超过当前时间')
			modelRef.practicalTime = nowDateTime()
		}
	}
</script>
